#include "tsp.h"

#ifdef __cplusplus
extern "C" {
#endif

int EncodeByte(unsigned char* out_buf, int out_buf_size, unsigned char in_)
{
    if (out_buf_size >= sizeof(unsigned char))
    {
        out_buf[0] = in_;
        return sizeof(unsigned char);
    }

    return 0;
}

int EncodeWord(unsigned char* out_buf, int out_buf_size, unsigned short in_)
{
    if (out_buf_size >= sizeof(unsigned short))
    {
        out_buf[0] = in_ >> 8;
        out_buf[1] = in_;
        return sizeof(unsigned short);
    }

    return 0;
}

int EncodeDWord(unsigned char* out_buf, int out_buf_size, unsigned int* in_)
{
    if (out_buf_size >= sizeof(unsigned int))
    {
        out_buf[0] = in_ >> 24;
        out_buf[1] = in_ >> 16;
        out_buf[2] = in_ >> 8;
        out_buf[3] = in_;
        return sizeof(unsigned int);
    }

    return 0;
}

int EncodeBytes(unsigned char* out_buf, int out_buf_size, unsigned char* in_, int in_len)
{
    if (out_buf_size >= in_len)
    {
        memset(out_buf, in_, in_len);
        return in_len;
    }

    return 0;
}

int TNetProtocolEncode(unsigned char* out_buf, int out_buf_size, TNetProtocolMsg* in_msg)
{
    if (in_msg && out_buf && out_buf_size >= sizeof(TNetProtocolMsg))
    {
        int encode_size = 0;

{%- for 消息结构表中的一个字段 in 消息结构表 %}
    {%- if [消息结构表中的一个字段[0]] == ["MsgBody"] %}
    union {
        {%- for 消息体类型 in 消息体字典.keys() %}
        TNetProtocolMsgBody{{消息体类型.split()[0]}} {{消息体类型.split()[0]}};
        {%- endfor %}
    } MsgBody;
    {%- else %}
        {%- if [消息结构表中的一个字段[2]] == ["BYTE"] %}
        encode_size += EncodeByte(&out_buf[encode_size], out_buf_size - encode_size, in_msg->{{[消息结构表中的一个字段[0]]}});
        {%- endfor %}
    {%- endif %}
{%- endfor %}
        return out_buf_size;
    }

    return -1;
}

int TNetProtocolDecode(TNetProtocolMsg* out_msg, unsigned char* in_buf, int in_buf_len)
{

}

#ifdef __cplusplus
}
#endif

# endif ///< _NET_PROTOCOL_H_
